﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using AutoMapper;
using Microsoft.AspNet.Identity;
using PublishNews.Entities;
using PublishNews.Models;
using PublishNews.Repositories;

namespace PublishNews.Controllers
{
    [Authorize]
    public class NewsController : Controller
    {
        public ILocationRepository LocationRepository;
        public INewsRepository NewsRepository;
        public UserManager<User> UserManager;

        public NewsController(ILocationRepository locationRepository, INewsRepository newsRepository, UserManager<User> userManager)
        {
            LocationRepository = locationRepository;
            NewsRepository = newsRepository;
            UserManager = userManager;
        }

        //
        // GET: /News/
        public ActionResult Index()
        {
            return View();
        }

        public async Task<ActionResult> Create()
        {
            return View(new CreateNewsModel());
        }

        [HttpPost, ValidateInput(false)]
        public async Task<ActionResult> Create(CreateNewsModel model)
        {
            model.UserId = User.Identity.GetUserId();
            if (ModelState.IsValid)
            {
                var news = Mapper.Map<News>(model);

                news.CreatedBy = User.Identity.GetUserName();
                news.CreatedDate = DateTime.Now;

                var result = await NewsRepository.Add(news);
                model.Succeeded = result > 0 ? true : false;
            }
            return View(model);
        }

        public async Task<ActionResult> Edit(Guid id)
        {
            var news = await NewsRepository.GetBy(id);

            var model = Mapper.Map<CreateNewsModel>(news);
            return View(model);
        }

        [HttpPost, ValidateInput(false)]
        public async Task<ActionResult> Edit(CreateNewsModel model)
        {
            model.UserId = User.Identity.GetUserId();
            if (ModelState.IsValid)
            {
                var news = Mapper.Map<News>(model);

                news.UpdatedBy = User.Identity.GetUserName();
                news.UpdatedDate = DateTime.Now;

                var result = await NewsRepository.Update(news);
                model.Succeeded = result > 0 ? true : false;
            }
            return View(model);
        }

        [HttpPost]
        public JsonResult Upload()
        {
            if (Request.Files.Count > 0)
            {
                Uri uri = HttpContext.Request.Url;
                string host = "";
                if (uri.Port != 80)
                {
                    host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
                }
                else
                {
                    host = uri.Scheme + Uri.SchemeDelimiter + uri.Host;
                }

                HttpPostedFileBase hpf = Request.Files[0];

                string extension = Path.GetExtension(hpf.FileName);
                var oldFileName = Path.GetFileName(hpf.FileName);
                string newFileName = Guid.NewGuid().ToString() + extension;
                int width = 0;
                int height = 0;

                if (hpf != null && hpf.ContentLength > 0)
                {
                    var path = Path.Combine(Server.MapPath("~/Images/"), newFileName);
                    hpf.SaveAs(path);
                    Image image = Image.FromFile(path);
                    height = image.Height;
                    width = image.Width;
                }
                return Json(new
                {
                    upload = new
                    {
                        links = new { original = host + "/Images/" + newFileName },
                        image = new { width = "", height = "" }
                    }
                }, JsonRequestBehavior.AllowGet);
            }
            return Json(null, JsonRequestBehavior.AllowGet);
        }


        public JsonResult GetAllNews()
        {
            var entity = NewsRepository.DbSet().OrderBy(x => x.Title);
            var model = Mapper.Map<List<ViewNewsModel>>(entity);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public async Task<JsonResult> Delete(Guid newsId)
        {
            var result = await NewsRepository.Remove(newsId);
            return Json(result > 0 ? true : false, JsonRequestBehavior.AllowGet);
        }

        public ActionResult TestNews()
        {
            return View();
        }
    }
}
